<?php
require_once 'Zend/Loader/Autoloader.php';
require_once 'Zend/Loader/Autoloader/Interface.php';
require_once 'Engine/Functions.php';
require_once 'Engine/Loader.php';

class Bootstrap {
	private $_config = null;
	private $_module = null;

	protected $_moduleNames = array(
		'admin'     => 'admin',
	);

    public function run() {
    	$this->setLoader();
		$this->setConfig();
		$this->setLogger();
		$this->setDbAdapter();
		$this->setSession();
        $this->setFront();
        $this->setAcl();
        $this->setView();

       	$response = Zend_Controller_Front::getInstance()->dispatch();

		$response
			->sendHeaders()
			->outputBody()
		;
	}

	/**
     * Настройка загрузчика
     */
    protected function setLoader() {
        Zend_Loader_Autoloader::getInstance()
			->pushAutoloader(new Cornholio_Loader())
			->registerNamespace('Engine_');
    }

    protected function setConfig()
    {
		$subdomain = explode ('.', $_SERVER['HTTP_HOST']);
    	$subdomain = ($subdomain[0] != 'www') ? $subdomain[0] : $subdomain[1];

		$this->_module = array_key_exists($subdomain, $this->_moduleNames) ? $this->_moduleNames[$subdomain] : 'default';

		$this->_config = new Zend_Config_Xml(ROOT . '/application/config.xml', APPLICATION_ENVIRONMENT, true);

		$this->_config->module  = new Zend_Config($this->_config->modules->{$this->_module}->toArray());

    	Zend_Registry::set('config', $this->_config);

		set_include_path(get_include_path() . PATH_SEPARATOR . ROOT . $this->_config->paths->modules . '/' . $this->_module . '/controllers');

		define('MODULE_PATH', ROOT . $this->_config->paths->modules . $this->_module);
    }

    protected function setLogger()
    {
		if ($this->_config->debug->isOn) {
	    	$logger = new Zend_Log();
			$writer = new Zend_Log_Writer_Firebug();

			$logger->addWriter($writer);

			Zend_Registry::set('logger', $logger);
		}
    }

    protected function setSession() {
		Zend_Session::start();
    }

	/**
     * Настройка вида
     */
    protected function setView() {
        Zend_Layout::startMvc();
        
        $layout = Zend_Layout::getMvcInstance();

	    $layout->setLayoutPath(ROOT . $this->_config->paths->modules . $this->_module . '/layouts');

        $view = $layout->getView();

        $view->baseUrl = $this->_config->host->baseUrl;
		$view->doctype('XHTML1_STRICT');

        $view->addHelperPath('Engine/View/Helper', 'Engine_View_Helper');
		$view->addHelperPath($this->_module . '/views/helpers', $this->_module . '_helpers');

        $layout->setView($view);
    }

    /**
     * Установка соединения с базой данных и помещение его объекта в реестр.
     */
    protected function setDbAdapter() {
        $db = Zend_Db::factory($this->_config->db);

		if ($this->_config->debug->isOn) {
			$profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
			$profiler->setEnabled(true);

			$db->setProfiler($profiler);
		}

		$db->setFetchMode(Zend_Db::FETCH_OBJ);

		$db->query("set @@SESSION.sql_mode = ''");
        $db->query("SET NAMES UTF8");

        Zend_Db_Table_Abstract::setDefaultAdapter($db);

        Zend_Registry::set('db', $db);
    }

    /**
     * Настройка маршрутов
     */
    protected function setFront() {
		$router = new Zend_Controller_Router_Rewrite();

		$router->addConfig(new Zend_Config_Xml(ROOT . $this->_config->paths->modules . $this->_module . '/config/routes.xml'));

		$front = Zend_Controller_Front::getInstance();

		$front
        	->setBaseUrl($this->_config->host->baseUrl)
            ->returnResponse(true)
            ->setRouter($router)
            ->addModuleDirectory(ROOT . $this->_config->paths->modules)
            ->setDefaultModule($this->_module);
    }

    /**
     * Sets ACL
     */
	protected function setAcl() {
		Zend_Controller_Front::getInstance()->_acl = new Engine_Acl_Xml(ROOT . $this->_config->paths->modules . $this->_module . '/config/acl.xml');
	}
}